package com.iot.protocol.iec104.server.slave.handler;

import com.iot.protocol.iec104.bean.SqlSessionProvider;
import com.iot.protocol.iec104.bean.WeatherParameters;
import com.iot.protocol.iec104.common.BasicInstruction104;
import com.iot.protocol.iec104.dao.WeatherParametersMapper;
import com.iot.protocol.iec104.message.MessageDetail;
import com.iot.protocol.iec104.server.handler.ChannelHandler;
import com.iot.protocol.iec104.server.handler.DataHandler;
import com.iot.protocol.util.Iec104Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.Timer;
import java.util.TimerTask;

@Slf4j
public class Iec104SlaveDataHandle implements DataHandler {
    private Timer timer;
    @Override
    public void handlerAdded(ChannelHandler ctx) throws Exception {
//         创建一个新的定时器对象
        this.timer = new Timer();

        // 创建一个任务（需要在指定时间后执行）
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
//                System.out.println("定时器触发了！");
//                更改下面这行
                SqlSession session = SqlSessionProvider.getSqlSession();
                WeatherParametersMapper mapper = session.getMapper(WeatherParametersMapper.class);
                WeatherParameters weatherparam = mapper.getLastWeatherParameters();

                if(weatherparam!=null){
                    short reason =3;
                    MessageDetail Detail104n = Iec104Util.generateMessageDetail(weatherparam, reason);
                    ctx.writeAndFlush(Detail104n);
                }
//                ctx.writeAndFlush(BasicInstruction104.getGeneralCallEndDetail104());
            }
        };
        // 设置定时器任务的开始时间为1000ms之后，并且每隔2000ms重复执行一次
        long delay = 5000; // 初始延迟时间
        long period = 1000*60*5; // 重复周期
        this.timer.scheduleAtFixedRate(task, delay, period);
    }

    @Override
    public void handlerEnd(ChannelHandler ctx) throws Exception {
        this.timer.cancel();
    }

    @Override
    public void channelRead(ChannelHandler ctx, MessageDetail detail104) throws Exception {
        ctx.writeAndFlush(BasicInstruction104.getGeneralCallReplyDetail104());

        SqlSession session = SqlSessionProvider.getSqlSession();
        WeatherParametersMapper mapper = session.getMapper(WeatherParametersMapper.class);
        WeatherParameters weatherparam = mapper.getLastWeatherParameters();

        if(weatherparam!=null){
            short reason =5;
            MessageDetail Detail104n = Iec104Util.generateMessageDetail(weatherparam, reason);
//            log.info("准备发送报文：" + Detail104n.toString());
            ctx.writeAndFlush(Detail104n);
            ctx.writeAndFlush(BasicInstruction104.getGeneralCallEndDetail104());
        }
    }
}
